/**
 * Created by kevin on 2017/6/6.
 */

var spawn = require('child_process').spawn;
var fs = require('fs');
function scripter() {
    
}

scripter.execute = function (shell,normalCallback,errCallback,finishCallback,ip) {
    var shellComponents = shell.toString().split(' ');

    var first = null;

    if (ip && ip.length > 0) {
        shellComponents.unshift(ip);
        shellComponents.unshift('22');
        shellComponents.unshift('-p');
        shellComponents.unshift('-t');
        shellComponents.unshift('-t');
        first = 'ssh';
    } else  {
        first = shellComponents.shift();
    }
    var child = spawn(first,shellComponents);

    if (normalCallback) {
        child.stdout.on('data',function (data) {
            normalCallback(data.toString())
        })
    }

    if (errCallback) {
        child.stderr.on('data',function (data) {
            var str = data.toString();
            if (str.indexOf('Connection to') >= 0 && str.indexOf('closed.') >= 0) {
                return;
            }
            errCallback(str);
        })
    }

    if (finishCallback) {
        child.on('exit', function (code) {
            finishCallback(code)
            console.log('child process exited with code ' + code);
        });
    }
    child.on('error', function (err) {

        console.log('exec error: ' + err);
    });
};

scripter.executeAndroid = function (shell,normalCallback,errCallback,finishCallback) {
    var shellComponents = shell.toString().split(' ');
    var first = shellComponents.shift();
    var others = shellComponents.join(' ');
    var shellPath = './public/scripts/'+first;
    // var child = spawn('chmod',['+x',shellPath]);
    // child.stdout.on('data',function (data) {
    //     console.log(data.toString())
    // })
    // child.stderr.on('data',function (data) {
    //     console.log(data)
    // })
    // child.stdout.on('exit',function (code) {
    //     console.log('not go here ' + code);
    //     code = parseInt(code);
    //     if (code === 0) {
    //
    //         var shell = shellPath + ' ' + others;
    //         console.log('shell info: ' + shell);
    //         scripter.execute(shell ,normalCallback,errCallback,finishCallback);
    //     } else {
    //         finishCallback(code);
    //     }
    // })
    var shell = shellPath + ' ' + others;
    console.log('shell info: ' + shell);
    scripter.execute(shell ,normalCallback,errCallback,finishCallback);
};

module.exports = scripter;